<?php
namespace app\admin\controller;

use app\common\model\Coupon as CouponModel;
use app\common\controller\AdminBase;
use think\Config;
use think\Db;

class Coupon extends AdminBase
{
    protected $coupon_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->coupon_model = new CouponModel();
    }

    /**
     * 管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index($keyword = '', $page = 1)
    {
        $map = [];
        if ($keyword) {
            $map['name'] = ['like', "%{$keyword}%"];
        }
        $coupon_list = $this->coupon_model->where($map)->order('id DESC')->paginate(15, false, ['page' => $page]);

        return $this->fetch('index', ['coupon_list' => $coupon_list, 'keyword' => $keyword]);
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'coupon');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->coupon_model->allowField(true)->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $coupon = $this->coupon_model->find($id);

        return $this->fetch('edit', ['coupon' => $coupon]);
    }

    /**
     * 更新
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'coupon');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->coupon_model->allowField(true)->save($data, $id) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除
     * @param $id
     */
    public function delete($id)
    {
        $fileImg = $this->coupon_model->where('id',$id)->value('photo');
        if($fileImg){
           if(file_exists('./'.$fileImg)){
               unlink('./'.$fileImg);
           } 
        }        
        if ($this->coupon_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    
}